import React, { useState } from 'react';
import { Download, Star, Search, Filter, Eye, ShoppingCart, Zap, Shield, Award } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

const PluginStore = ({ toggleSidebar }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [sortBy, setSortBy] = useState('popular');

  // 模拟插件数据
  const plugins = [
    {
      id: 1,
      name: '文件管理增强',
      description: '提供更强大的文件管理功能，支持批量操作和高级搜索',
      category: 'productivity',
      version: '2.1.0',
      downloads: 15420,
      rating: 4.8,
      price: 0,
      author: 'DevTeam',
      tags: ['文件管理', '效率工具'],
      featured: true
    },
    {
      id: 2,
      name: 'API调试助手',
      description: '专业的API测试和调试工具，支持多种请求格式',
      category: 'development',
      version: '1.5.2',
      downloads: 8930,
      rating: 4.6,
      price: 29.99,
      author: 'APITools Inc',
      tags: ['API', '开发工具', '调试']
    },
    {
      id: 3,
      name: '数据可视化',
      description: '强大的图表和数据可视化组件库',
      category: 'analytics',
      version: '3.0.1',
      downloads: 12650,
      rating: 4.9,
      price: 0,
      author: 'ChartMaster',
      tags: ['图表', '数据分析', '可视化']
    },
    {
      id: 4,
      name: '主题定制器',
      description: '自定义系统主题和样式的强大工具',
      category: 'design',
      version: '1.8.0',
      downloads: 6780,
      rating: 4.4,
      price: 19.99,
      author: 'ThemeStudio',
      tags: ['主题', '设计', '定制']
    }
  ];

  const categories = [
    { value: 'all', label: '全部分类' },
    { value: 'productivity', label: '效率工具' },
    { value: 'development', label: '开发工具' },
    { value: 'analytics', label: '数据分析' },
    { value: 'design', label: '设计工具' },
    { value: 'security', label: '安全工具' }
  ];

  const filteredPlugins = plugins.filter(plugin => {
    const matchesSearch = plugin.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         plugin.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         plugin.tags.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase()));
    const matchesCategory = selectedCategory === 'all' || plugin.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  const sortedPlugins = [...filteredPlugins].sort((a, b) => {
    switch (sortBy) {
      case 'popular':
        return b.downloads - a.downloads;
      case 'rating':
        return b.rating - a.rating;
      case 'newest':
        return b.id - a.id;
      case 'price-low':
        return a.price - b.price;
      case 'price-high':
        return b.price - a.price;
      default:
        return 0;
    }
  });

  const getRatingStars = (rating) => {
    const stars = [];
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 !== 0;

    for (let i = 0; i < fullStars; i++) {
      stars.push(<Star key={i} className="w-4 h-4 fill-yellow-400 text-yellow-400" />);
    }

    if (hasHalfStar) {
      stars.push(<Star key="half" className="w-4 h-4 fill-yellow-400/50 text-yellow-400" />);
    }

    const emptyStars = 5 - Math.ceil(rating);
    for (let i = 0; i < emptyStars; i++) {
      stars.push(<Star key={`empty-${i}`} className="w-4 h-4 text-gray-300" />);
    }

    return stars;
  };

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl flex items-center justify-center">
                  <Download className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    插件商店
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    发现和安装强大的功能插件
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <Button variant="outline">
                <Eye className="w-4 h-4 mr-2" />
                我的插件
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        {/* 统计信息 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">可用插件</p>
                  <p className="text-2xl font-bold text-material-grey-900">{plugins.length}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Download className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">热门插件</p>
                  <p className="text-2xl font-bold text-orange-600">
                    {plugins.filter(p => p.downloads > 10000).length}
                  </p>
                </div>
                <div className="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                  <Zap className="w-6 h-6 text-orange-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">免费插件</p>
                  <p className="text-2xl font-bold text-green-600">
                    {plugins.filter(p => p.price === 0).length}
                  </p>
                </div>
                <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                  <Shield className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">精选插件</p>
                  <p className="text-2xl font-bold text-purple-600">
                    {plugins.filter(p => p.featured).length}
                  </p>
                </div>
                <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                  <Award className="w-6 h-6 text-purple-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 搜索和筛选 */}
        <Card className="mb-6">
          <CardContent className="p-6">
            <div className="flex flex-col sm:flex-row gap-4">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <Input
                  placeholder="搜索插件名称、描述或标签..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10"
                />
              </div>
              
              <Select value={selectedCategory} onValueChange={setSelectedCategory}>
                <SelectTrigger className="w-full sm:w-48">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {categories.map(category => (
                    <SelectItem key={category.value} value={category.value}>
                      {category.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>

              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger className="w-full sm:w-48">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="popular">最受欢迎</SelectItem>
                  <SelectItem value="rating">评分最高</SelectItem>
                  <SelectItem value="newest">最新发布</SelectItem>
                  <SelectItem value="price-low">价格从低到高</SelectItem>
                  <SelectItem value="price-high">价格从高到低</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        {/* 插件列表 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {sortedPlugins.map((plugin) => (
            <Card key={plugin.id} className="hover:shadow-lg transition-shadow">
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center space-x-2 mb-2">
                      <CardTitle className="text-lg">{plugin.name}</CardTitle>
                      {plugin.featured && (
                        <Badge className="bg-gradient-to-r from-yellow-400 to-orange-500 text-white">
                          精选
                        </Badge>
                      )}
                    </div>
                    <p className="text-sm text-material-grey-600 mb-3">
                      {plugin.description}
                    </p>
                    <div className="flex items-center space-x-4 text-sm text-material-grey-500">
                      <span>v{plugin.version}</span>
                      <span>by {plugin.author}</span>
                    </div>
                  </div>
                </div>
              </CardHeader>
              
              <CardContent className="pt-0">
                <div className="space-y-4">
                  {/* 评分和下载量 */}
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-1">
                      {getRatingStars(plugin.rating)}
                      <span className="text-sm text-material-grey-600 ml-2">
                        {plugin.rating}
                      </span>
                    </div>
                    <div className="text-sm text-material-grey-600">
                      {plugin.downloads.toLocaleString()} 下载
                    </div>
                  </div>

                  {/* 标签 */}
                  <div className="flex flex-wrap gap-1">
                    {plugin.tags.map((tag, index) => (
                      <Badge key={index} variant="secondary" className="text-xs">
                        {tag}
                      </Badge>
                    ))}
                  </div>

                  {/* 价格和操作按钮 */}
                  <div className="flex items-center justify-between pt-2">
                    <div className="text-lg font-bold">
                      {plugin.price === 0 ? (
                        <span className="text-green-600">免费</span>
                      ) : (
                        <span className="text-material-grey-900">¥{plugin.price}</span>
                      )}
                    </div>
                    <div className="flex space-x-2">
                      <Button variant="outline" size="sm">
                        <Eye className="w-4 h-4 mr-1" />
                        详情
                      </Button>
                      <Button size="sm" className="bg-primary hover:bg-primary-600">
                        <ShoppingCart className="w-4 h-4 mr-1" />
                        {plugin.price === 0 ? '安装' : '购买'}
                      </Button>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>

        {/* 空状态 */}
        {sortedPlugins.length === 0 && (
          <Card>
            <CardContent className="py-12">
              <div className="text-center">
                <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                  <Download className="w-8 h-8 text-material-grey-500" />
                </div>
                <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                  未找到匹配的插件
                </h3>
                <p className="text-material-grey-500">
                  尝试使用不同的关键词或筛选条件
                </p>
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </>
  );
};

export default PluginStore;
